package com.ladybug.flow.common.security.config;

import com.alibaba.fastjson.JSON;
import com.ladybug.flow.common.exception.enums.ErrorEnum;
import com.ladybug.flow.common.vo.ResponseResult;
import org.springframework.http.MediaType;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
* @description: 处理非法请求
* @author long
* @date 2022/10/18 8:25
* @version 1.0
*/
@Component
public class AuthenticationExceptionHandler implements AuthenticationEntryPoint {
    @Override
    public void commence(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e) throws IOException, ServletException {
        httpServletResponse.setContentType(MediaType.APPLICATION_JSON_VALUE);
        httpServletResponse.setStatus(HttpServletResponse.SC_FORBIDDEN);
        // 未登录
        if (e instanceof InsufficientAuthenticationException) {
            httpServletResponse.getWriter().write(JSON.toJSONString(ResponseResult.error(ErrorEnum.ILLEGAL_TOKEN)));
        }
    }
}
